<template lang="pug">
  view
    view.header(:style="{position:headerPosition,top:headerTop}")
      view.target(v-for="(target,index) in orderbyList"  @tap="select(index)"  :key="index"  :class="[target.selected?'on':'']")
        span {{ target.text }}
        view.icon(:class="target.orderbyicon[target.orderby]")
    view.place
    view.goods-list
      view.product-list
        view.product(v-for="(goods) in goodsList"  :key="goods.key"  @tap="toGoods(goods)")
          image(mode="widthFix"  :src="goods.img")
          view.solan
            view.name {{goods.name}}
            view.sub_title {{goods.slogan}}
            view.info
              view.price 价格:¥{{goods.price}}
              view.slogan 距离:{{goods.distance | distance}}
            view.info
              view.slogan {{goods.shopName}}
              view.slogan 进店>
      view.loading-text {{ loadingText }}
    view.popup.spec(:class="specClass"  @touchmove.stop.prevent="discard"  @tap="hideSpec")
      view.mask
      view.layer(@tap.stop="discard")
        view.content
          view.title 选择品牌：
          view.sp
            view(v-for="(item,index) in goodsData.brand"  :class="[item.brand_id==selectBrand?'on':'']"  @tap="setSelectBrand(item)"  :key="index") {{ item.name }}
          view.title 选择属性：
          view.sp
            view(v-for="(item,index) in goodsData.attribute"  :class="[item.id==selectAttribute?'on':'']"  @tap="setSelectAttribute(item)"  :key="index") {{ item.name }}
          view.title 选择规格：
          view.sp
            view(v-for="(item,index) in goodsData.standard"  :class="[item.id==selectSpec?'on':'']"  @tap="setSelectSpec(item)"  :key="index") {{ item.name }}
        view.btn
          view.button(@tap="hideSpec") 完成
    view.popup.cat(:class="catClass"  @touchmove.stop.prevent="discard"  @tap="hideCat")
      view.mask
      view.layer(@tap.stop="discard")
        view.content
          view.title 选择大类：
          view.sp
            view(v-for="(item,index) in categoryList"  :class="[item.id==selectCat?'on':'']"  @tap="setSelectCat(item)"  :key="index") {{ item.title }}
          view.title 选择小类：
          view.sp
            view(v-for="(item,index) in classList"  :class="[item.id==selectClass?'on':'']"  @tap="setSelectClass(item)"  :key="index") {{ item.name }}
        view.btn
          view.button(@tap="hideCat") 完成
</template>

<script>
export default {
  data() {
    return {
      //session
      sessionid: '',
      hearder: '',
      productCategoryId: '-1',
      categoryList: [],
      selectCat: -1,
      classList: [],
      selectClass: -1,
      indexClass: -1,
      indexClassName: "",
      catClass: '', //分类弹窗css类，控制开关动画
      specClass: '', //规格弹窗css类，控制开关动画
      shareClass: '', //分享弹窗css类，控制开关动画
      goodsList: [],

      // 商品信息
      goodsData: {},
      totalPage: 0,
      currentPage: 1,
      pageSize: 40,
      loadindex: 0,
      loadingText: "正在加载...",
      headerTop: "0px",
      headerPosition: "fixed",
      orderbyList: [{
        text: "距离",
        selected: true,
        orderbyicon: ['sheng', 'jiang'],
        orderby: 0
      },
        {
          text: "价格",
          selected: false,
          orderbyicon: ['sheng', 'jiang'],
          orderby: 1
        },
        {
          text: "分类",
          selected: false,
          orderbyicon: false,
          orderby: 0
        },
        {
          text: "筛选",
          selected: false,
          orderbyicon: false,
          orderby: 0
        },
      ],

      orderby: "sheng",
      selectSpec: null, //选中规格

      selectBrand: -1,//选中品牌
      selectAttribute: -1,//选中属性

      standardName: "",

    };
  },
  filters: {
    distance(value) {
      if (value / 1000 > 1) return (value / 1000).toFixed(1) + "公里";
      else return value + "米";
    }
  },
  onLoad: function (option) { //option为object类型，会序列化上个页面传递的参数
    uni.setNavigationBarTitle({
      title: option.name
    });
    this.productCategoryId = option.cid;
    this.loadProductList();
    //兼容H5下排序栏位置
    // #ifdef H5
    //定时器方式循环获取高度为止，这么写的原因是onLoad中head未必已经渲染出来。
    let Timer = setInterval(() => {
      let uniHead = document.getElementsByTagName('uni-page-head');
      if (uniHead.length > 0) {
        this.headerTop = uniHead[0].offsetHeight + 'px';
        clearInterval(Timer); //清除定时器
      }
    }, 1);
    // #endif
    this.loadCatList();
  },
  onPageScroll(e) {
    //兼容iOS端下拉时顶部漂移
    if (e.scrollTop >= 0) {
      this.headerPosition = "fixed";
    } else {
      this.headerPosition = "absolute";
    }
  },
  //下拉刷新，需要自己在page.json文件中配置开启页面下拉刷新 "enablePullDownRefresh": true
  onPullDownRefresh() {
    setTimeout(() => {
      //this.reload();
      uni.stopPullDownRefresh();
    }, 1000);
  },
  //上拉加载，需要自己在page.json文件中配置"onReachBottomDistance"
  onReachBottom() {
    // uni.showToast({
    // 	title: '触发上拉加载'
    // });
    if (this.currentPage >= this.totalPage) {

      this.loadingText = "到底了";
      return false;
    } else {
      this.loadingText = "加载中...";
      this.loadProductList();
    }
  },
  methods: {
    reload() {
      console.log("reload");
      this.goodsList = [];
      // let tmpArr = []
      // this.goodsList = [];
      // let end_goods_id = 0;
      // for(let i=1;i<=10;i++){
      // 	let goods_id = end_goods_id+i;
      // 	let p = { goods_id: goods_id, img: 'http://120.55.49.138/ShopMall/static/img/goods/p'+(goods_id%10==0?10:goods_id%10)+'.jpg', name: '商品名称商品名称商品名称商品名称商品名称', price: '￥168', slogan:'1235人付款' };
      // 	this.goodsList.push(p);
      // }
    },
    loadCatList: function () {
      //var indexNav = this.$SysCache.get("app_index_productlist");
      var indexCat = false;
      if (indexCat) {
        this.categoryList = indexCat;
      } else {
        this.$Request.get(this.$api.home.withChildren).then(res => {
          //
          if (res.code == 200) {
            this.categoryList = [];

            var array = res.data;
            for (var i = 0; i < array.length; i++) {
              //console.log(i,array[i]);
              var item = array[i];
              var data = {
                'id': item.id,
                'title': item.name,
                'banner': 'http://120.55.49.138/ShopMall/static/img/category/banner.jpg',
              }
              var children = array[i].children;
              var list = [];
              for (var j = 0; j < children.length; j++) {
                //console.log(i,array[i]);
                var itemlist = children[j];
                var datachildren = {
                  'id': itemlist.id,
                  'name': itemlist.name,
                  'img': itemlist.icon,
                }
                list.push(datachildren);
              }
              data.list = list;
              this.categoryList.push(data);
            }
            //this.$SysCache.put("app_index_productlist",res.data,86400);
          }
        })
      }
    },

    loadFilterList: function (id) {
      //var indexNav = this.$SysCache.get("app_index_productlist");
      var indexCat = false;
      if (indexCat) {
        this.goodsData = indexCat;
      } else {
        this.$Request.get(this.$api.product.getQueryDict + "?product_category_id=" + id).then(res => {

          if (res.code == 200) {
            this.goodsData = res.data;
            this.loadProductList();
            //this.$SysCache.put("app_index_productlist",res.data,86400);
          }
        })
      }
    },
    //大类点击，过滤二级分类
    setSelectCat(item) {
      this.selectCat = item.id;
      this.classList = item.list;
    },

    setSelectClass(item) {
      this.selectClass = item.id;
      this.loadFilterList(item.id);
    },
    //选中品牌
    setSelectBrand(item) {
      if (this.selectClass == -1) {
        this.filterCat();
        return;
      }
      this.selectBrand = item.brand_id;
    },
    //选中属性
    setSelectAttribute(item) {
      this.selectAttribute = item.id;

    },
    //分类弹窗
    showCat(fun) {
      this.catClass = 'show';
      this.catCallback = fun;
    },
    catCallback() {
      return;
    },
    //关闭规格弹窗
    hideCat() {
      this.catClass = 'hide';
      //回调

      this.selectClass && this.catCallback && this.catCallback();
      this.catCallback = false;
      setTimeout(() => {
        this.catClass = 'none';

      }, 200);
    },
    //商品跳转
    toGoods(e) {
      console.log(e);
      uni.showToast({
        title: '商品' + e.id,
        icon: 'none'
      });
      uni.navigateTo({
        url: '../../goods/goods?cid=' + e.id + "&shopId=" + e.shopId
      });
    },
    filterProduct() {
      this.showSpec(false);
    },
    filterCat() {
      this.showCat(false);
    },
    discard() {
      //丢弃
    },

    //排序类型
    select(index) {
      //筛选
      if (index == 2) {
        this.filterCat();
        return;
      }
      if (index == 3) {
        this.filterProduct();
        return;
      }
      let tmpTis = this.orderbyList[index].text + "排序 "
      if (this.orderbyList[index].orderbyicon) {
        let type = this.orderbyList[index].orderby == 0 ? '升序' : '降序';
        if (this.orderbyList[index].selected) {
          type = this.orderbyList[index].orderby == 0 ? '降序' : '升序';
          this.orderbyList[index].orderby = this.orderbyList[index].orderby == 0 ? 1 : 0;
          if (type == "降序") {
            this.goodsList.sort(function (a, b) {
              // console.log(a);
              return b.price - a.price;
            })
          } else {
            this.goodsList.sort(function (a, b) {
              // console.log(a);
              return a.price - b.price;
            })
          }
        }
        tmpTis += type
      }
      this.orderbyList[index].selected = true;
      let len = this.orderbyList.length;
      for (let i = 0; i < len; i++) {
        if (i != index) {
          this.orderbyList[i].selected = false;
        }
      }

      uni.showToast({
        title: tmpTis,
        icon: "none"
      });
    },
    loadProductList: function () {
      this.sessionid = uni.getStorageSync("sessionid");
      this.hearder = uni.getStorageSync("hearder");

      if (this.sessionid == null || this.sessionid == '') {
        //uni.showToast({title: "请先登录！"});
        uni.navigateTo({
          url: '../login/login'
        })
        return;
      }
      var header = this.hearder;
      var sessionid = this.sessionid;
      if (this.currentPage == 1) {
        this.goodsList = [];
      } else
        this.currentPage++;
      var urlpage = "?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize;
      //var indexNav = this.$SysCache.get("app_index_productlist");
      var indexNav = false;
      if (indexNav) {
        this.goodsList = indexNav;
      } else {

        var lat = uni.getStorageSync("lat");
        var lon = uni.getStorageSync("lon");
        var param = {
          "latitude": lat,
          "longitude": lon,
          "promotion_status": 3,
          "publishStatus": 1
        };
        if (this.selectBrand > -1) param.brandId = this.selectBrand;
        if (this.selectSpec != null) param.standardName = this.standardName;


        if (this.selectClass > -1) {
          param.productCategoryId = this.selectClass;
          //param = "?pageNum=1&pageSize=5&productCategoryId="+this.productCategoryId;
        }


        this.$Request.post(this.$api.product.listProductWithDistance + urlpage, param, this.hearder + ' ' + this
            .sessionid).then(
            res => {

              if (res.code == 200) {
                // var arrayCategory = res.data.list;
                // for (var i = 0; i < arrayCategory.length; i++) {
                // 	var goodsdata = arrayCategory[i];
                // 	var goodsitem = {
                // 		id: goodsdata.id,
                // 		name: goodsdata.name,
                // 		img: goodsdata.icon,
                // 		productCount: goodsdata.product_count,
                // 	};
                // 	this.categoryList.push(goodsitem);
                // }
                var array = res.data.list;
                for (var i = 0; i < array.length; i++) {
                  var goodsdata = array[i];


                  var goodsitem = {
                    id: goodsdata.id,
                    shopId: goodsdata.shop_id,
                    goods_id: goodsdata.id,
                    productId: goodsdata.id,
                    img: goodsdata.pic,
                    name: goodsdata.name,
                    slogan: goodsdata.sub_title,
                    price: goodsdata.price,
                    originalPrice: goodsdata.original_price,
                    shopName: goodsdata.shop_name,
                    brandName: goodsdata.brand_name,
                    productCategoryId: goodsdata.product_category_id,
                    distance: goodsdata.distance,
                    stock: goodsdata.stock,
                    key: `${goodsdata.shop_id}+${goodsdata.id}`
                  };
                  console.log(`${goodsdata.shop_id}+${goodsdata.id}`)
                  this.goodsList.push(goodsitem);
                }
                //this.$SysCache.put("app_index_productlist",res.data,86400);
              }
            })
      }
    },
    //选择规格
    setSelectSpec(item) {
      this.selectSpec = item.id;
      this.standardName = item.name;
    },
    //规格弹窗
    showSpec(fun) {
      this.specClass = 'show';
      this.specCallback = fun;
    },
    specCallback() {
      return;
    },
    //关闭规格弹窗
    hideSpec() {
      this.specClass = 'hide';
      //回调

      this.selectSpec && this.specCallback && this.specCallback();
      this.specCallback = false;
      setTimeout(() => {
        this.specClass = 'none';
        this.loadProductList();
      }, 200);
    },
  }

}
</script>

<style lang="scss">
@keyframes showPopup {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

@keyframes hidePopup {
  0% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}

@keyframes showLayer {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-100%);
  }
}

@keyframes hideLayer {
  0% {
    transform: translateY(-100%);
  }

  100% {
    transform: translateY(0);
  }
}

.icon {
  font-size: 26upx;
}

.header {
  width: 92%;
  padding: 0 4%;
  height: 79upx;
  display: flex;
  justify-content: space-around;
  align-items: flex-end;
  position: fixed;
  top: 0;
  z-index: 10;
  background-color: #fff;
  border-bottom: solid 1upx #eee;

  .target {
    width: 20%;
    height: 60upx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 28upx;
    margin-bottom: -2upx;
    color: #aaa;

    &.on {
      color: #555;
      border-bottom: 4upx solid #f06c7a;
      font-weight: 600;
      font-size: 30upx;
    }


  }
}

.place {

  background-color: #ffffff;
  height: 100upx;

}

.category-list {
  width: 92%;
  margin: 0 4%;
  padding: 0 0 30upx 0;
  border-bottom: solid 2upx #f6f6f6;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;

  .category {
    width: 25%;
    margin-top: 50upx;
    display: flex;
    flex-wrap: wrap;

    .img {
      width: 100%;
      display: flex;
      justify-content: center;

      image {
        width: 9vw;
        height: 9vw;
      }
    }

    .text {
      margin-top: 16upx;
      width: 100%;
      display: flex;
      justify-content: center;
      font-size: 24upx;
      color: #3c3c3c;
    }
  }
}

.goods-list {
  .loading-text {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 60upx;
    color: #979797;
    font-size: 24upx;
  }

  .sub_title {
    width: 92%;
    padding: 10upx 4%;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    text-align: justify;
    overflow: hidden;
    color: #979797;
    font-size: 26upx;
  }

  .product-list {
    width: 92%;
    padding: 0 4% 3vw 4%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .product {
      width: 100%;
      display: flex;
      border-radius: 20upx;
      background-color: #fff;
      margin: 0 0 15upx 0;
      box-shadow: 0upx 5upx 25upx rgba(0, 0, 0, 0.1);

      image {
        width: 30%;
        // border-radius: 20upx 20upx 0 0;
      }

      .solan {
        width: 70%;

        .company {
          width: 92%;
          padding: 10upx 4%;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          text-align: justify;
          overflow: hidden;
          font-size: 34upx;
        }

        .name {
          width: 92%;
          padding: 10upx 4%;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          text-align: justify;
          overflow: hidden;
          font-size: 30upx;
        }

        .info {
          display: flex;
          justify-content: space-between;
          align-items: flex-end;
          width: 92%;
          padding: 10upx 4% 10upx 4%;

          .price {
            color: #e65339;
            font-size: 30upx;
            font-weight: 600;
          }

          .slogan {
            color: #807c87;
            font-size: 24upx;
          }
        }
      }
    }


  }
}

.spec {
  .row {
    width: 100%;
    display: flex;
    align-items: center;
    margin: 0 0 30upx 0;

    .text {
      font-size: 24upx;
      color: #a2a2a2;
      margin-right: 20upx;
    }

    .content {
      font-size: 28upx;
      display: flex;
      flex-wrap: wrap;

      .serviceitem {
        margin-right: 10upx;
      }

      .sp {
        width: 100%;
        display: flex;

        view {
          background-color: #f6f6f6;
          padding: 5upx 10upx;
          color: #999;
          margin-right: 10upx;
          font-size: 20upx;
          border-radius: 5upx;

          &.on {
            border: solid 1upx #f47952;
            padding: 4upx 8upx;
          }
        }
      }

      .sp_class {
        width: 20%;
        display: flex;

        view {
          background-color: #f6f6f6;
          padding: 5upx 10upx;
          color: #999;
          margin-right: 10upx;
          font-size: 20upx;
          border-radius: 5upx;

          &.on {
            border: solid 1upx #f47952;
            padding: 4upx 8upx;
          }
        }
      }
    }

    .arrow {
      position: absolute;
      right: 4%;

      .icon {
        color: #ccc;
      }
    }
  }
}


.cat {
  .row {
    width: 100%;
    display: flex;
    align-items: center;
    margin: 0 0 30upx 0;

    .text {
      font-size: 24upx;
      color: #a2a2a2;
      margin-right: 20upx;
    }

    .content {
      font-size: 28upx;
      display: flex;

      .serviceitem {
        margin-right: 10upx;
      }

      .sp {
        width: 100%;
        display: flex;

        view {
          background-color: #f6f6f6;
          padding: 5upx 10upx;
          color: #999;
          margin-right: 10upx;
          font-size: 20upx;
          border-radius: 5upx;

          &.on {
            border: solid 1upx #f47952;
            padding: 4upx 8upx;
          }
        }
      }
    }

    .arrow {
      position: absolute;
      right: 4%;

      .icon {
        color: #ccc;
      }
    }
  }
}

.popup {
  position: fixed;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 20;
  display: none;

  .mask {
    position: fixed;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 21;
    background-color: rgba(0, 0, 0, 0.6);
  }

  .layer {
    position: fixed;
    z-index: 22;
    bottom: -70%;
    width: 92%;
    padding: 0 4%;
    height: 70%;
    border-radius: 20upx 20upx 0 0;
    background-color: #fff;
    display: flex;
    flex-wrap: wrap;
    align-content: space-between;

    .content {
      width: 100%;
      padding: 20upx 0;
    }

    .btn {
      width: 100%;
      height: 100upx;

      .button {
        width: 100%;
        height: 80upx;
        border-radius: 40upx;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f47952;
        font-size: 28upx;
      }
    }
  }

  &.show {
    display: block;

    .mask {
      animation: showPopup 0.2s linear both;
    }

    .layer {
      animation: showLayer 0.2s linear both;
    }
  }

  &.hide {
    display: block;

    .mask {
      animation: hidePopup 0.2s linear both;
    }

    .layer {
      animation: hideLayer 0.2s linear both;
    }
  }

  &.none {
    display: none;
  }

  &.service {
    .row {
      margin: 30upx 0;

      .title {
        font-size: 30upx;
        margin: 10upx 0;
      }

      .description {
        font-size: 28upx;
        color: #999;
      }
    }
  }

  &.spec {
    .title {
      font-size: 30upx;
      margin: 30upx 0;
    }

    .sp {
      display: flex;

      view {
        font-size: 28upx;
        padding: 5upx 20upx;
        border-radius: 8upx;
        margin: 0 30upx 20upx 0;
        background-color: #f6f6f6;

        &.on {
          padding: 3upx 18upx;
          border: solid 1upx #f47925;
        }
      }
    }

    .length {
      margin-top: 30upx;
      border-top: solid 1upx #aaa;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 20upx;

      .text {
        font-size: 30upx;
      }

      .number {
        display: flex;
        justify-content: center;
        align-items: center;

        .input {
          width: 80upx;
          height: 60upx;
          margin: 0 10upx;
          background-color: #f3f3f3;
          display: flex;
          justify-content: center;
          align-items: center;
          text-align: center;

          input {
            width: 80upx;
            height: 60upx;
            display: flex;
            justify-content: center;
            align-items: center;
            text-align: center;
            font-size: 26upx;
          }
        }

        .sub,
        .add {
          width: 60upx;
          height: 60upx;
          background-color: #f3f3f3;
          border-radius: 5upx;

          .icon {
            font-size: 30upx;
            width: 60upx;
            height: 60upx;
            display: flex;
            justify-content: center;
            align-items: center;

          }
        }
      }
    }

  }

  &.cat {
    .title {
      font-size: 30upx;
      margin: 30upx 0;
    }

    .sp {
      display: flex;
      flex-wrap: wrap;

      view {
        font-size: 28upx;
        padding: 5upx 20upx;
        border-radius: 8upx;
        margin: 0 30upx 20upx 0;
        background-color: #f6f6f6;

        &.on {
          padding: 3upx 18upx;
          border: solid 1upx #f47925;
        }
      }
    }

    .length {
      margin-top: 30upx;
      border-top: solid 1upx #aaa;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 20upx;

      .text {
        font-size: 30upx;
      }

      .number {
        display: flex;
        justify-content: center;
        align-items: center;

        .input {
          width: 80upx;
          height: 60upx;
          margin: 0 10upx;
          background-color: #f3f3f3;
          display: flex;
          justify-content: center;
          align-items: center;
          text-align: center;

          input {
            width: 80upx;
            height: 60upx;
            display: flex;
            justify-content: center;
            align-items: center;
            text-align: center;
            font-size: 26upx;
          }
        }

        .sub,
        .add {
          width: 60upx;
          height: 60upx;
          background-color: #f3f3f3;
          border-radius: 5upx;

          .icon {
            font-size: 30upx;
            width: 60upx;
            height: 60upx;
            display: flex;
            justify-content: center;
            align-items: center;

          }
        }
      }
    }

  }
}
</style>
